#include "mythread.h"
#include <QElapsedTimer>
#include <QDebug>

Generate::Generate(QObject *parent) :
    QObject(parent)
{
}

void Generate::working(int m_num)
{
    qDebug() << "生成随机数的线程的线程地址： " << QThread::currentThread();
    QVector<int> list;
    QElapsedTimer time; // 统计时间 毫秒
    time.start();
    for(int i = 0; i < m_num; i++)
    {
        list.push_back(qrand() % 100000);
    }
    time.elapsed();
    int milsec = time.elapsed();
    qDebug() << "生成" << m_num << "个随机数总共用时：" << milsec << "毫秒";

    emit sendArray(list);
}

////////////////////////////////////////////////////////////
BubbleSort::BubbleSort(QObject *parent) :
    QObject(parent)
{

}


void BubbleSort::working(QVector<int> m_list)
{
    qDebug() << "冒泡排序的线程的线程地址： " << QThread::currentThread();
    QElapsedTimer time;
    time.start();
    int temp;
    for(int i =0;i<m_list.size();++i)
    {
        for(int j=0; j<m_list.size()-i-1; ++j)
        {
            if(m_list[j] > m_list[j+1])
            {
                temp = m_list[j];
                m_list[j] = m_list[j+1];
                m_list[j+1] = temp;
            }
        }
    }

    time.elapsed();
    int milsec = time.elapsed();
    qDebug() << "冒泡排序所用时间为 " << milsec << "毫秒";

    emit finish(m_list);
}

////////////////////////////////////////////////////////////


QuickSort::QuickSort(QObject *parent):
    QObject(parent)
{

}

void QuickSort::working(QVector<int> m_list)
{
    qDebug() << "快速排序的线程的线程地址： " << QThread::currentThread();
    QElapsedTimer time;
    time.start();
    quickSort(m_list,0,m_list.size()-1);
    time.elapsed();
    int milsec = time.elapsed();
    qDebug() << "快速排序所用时间为 " << milsec << "毫秒";

    emit finish(m_list);
}

void QuickSort::quickSort(QVector<int> &arr, int begin, int end)
{
    if(begin > end)
        return;
    int tmp = arr[begin];
    int i = begin;
    int j = end;
    while(i != j){
        while(arr[j] >= tmp && j > i)
            j--;
        while(arr[i] <= tmp && j > i)
            i++;
        if(j > i){
            int t = arr[i];
            arr[i] = arr[j];
            arr[j] = t;
        }
    }
    arr[begin] = arr[i];
    arr[i] = tmp;
    quickSort(arr, begin, i-1);
    quickSort(arr, i+1, end);

}
